package com.lzh.excel.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.WriteCellData;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

/**
 * @author zhehen.lu
 * @date 2025/8/3 14:26
 */
public class EasyExcelStringToLocalDateConverter implements Converter<String> {
    private static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

    public EasyExcelStringToLocalDateConverter() {
    }

    @Override
    public Class supportJavaTypeKey() {
        return String.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public WriteCellData<String> convertToExcelData(WriteConverterContext<String> context) throws Exception {
        String value = (String)context.getValue();
        if (value == null) {
            return new WriteCellData("");
        } else {
            DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");

            try {
                LocalDate localDate = fmt.parseLocalDateTime(value).toLocalDate();
                return new WriteCellData(localDate.toString());
            } catch (Exception e) {
                return new WriteCellData("");
            }
        }
    }
}

